<script setup>
import {onMounted, ref} from "vue";
import axios from "@/axios";
import moment from 'moment'
import cardWarp from './cardWarp.vue'
import task from './task.vue'
import socket from '@/utils/socket'
import {
  Download,
  Delete,
  RefreshLeft,
  Check,
  Close,
  Upload,
  Edit,
  Plus,
  Rank,
  Grid,
  Folder
} from '@element-plus/icons-vue'
import local from '@/axios/local'
import utils from '@/utils/storage'
import createOrUpload from './createOrUpload.vue'
import {ElMessage, ElMessageBox} from "element-plus";
import MoveToFolder from "@/views/cloud/moveToFolder.vue";
import FilePreview from "@/views/cloud/filePreview.vue";
const dataList = ref([])
const selection = ref([])
const cardRef = ref()
const taskRef = ref()
const showType = ref('grid')
const createOrUploadRef = ref()
const selectType = ref('all')
const parent_id = ref(null)
const moveRef = ref(null)
const filePreviewRef = ref(null)
const file_path = ref([])
const nav = ref([])
const Socket = new socket()

function getSelection() {
  return showType.value === 'grid' ? selection.value : cardRef.value.checkIdList

}

async function resetSearch() {
  parent_id.value = null
  file_path.value = []
  dataList.value = []
  await getFiles()
}

async function updateName(row) {
  if (row.is_folder !== 1) {
    if (row.newName.split('.').length === 1) return ElMessage.warning('名称格式错误')
  }

  await local.post('/cloud/updateCloudFilesName', {
    id: row.id,
    name: row.newName,
    task: {
      name: row.name,
      srcBucket: row.path,
      targetBucket: row.path.replace(row.name, row.newName)
    }
  })
  await getFiles()
  row.is_rename = false
}

function move(item) {
  let arr = item ? [item] : getSelection()
  if (!arr.length) return
  moveRef.value?.show(arr)
}

async function batchDownload(item) {
  let arr = item ? [item] : getSelection()
  // 批量下载
  if (!arr.length) return
  let ids = arr.map(el => el.id)
  let res = await local.post('/cloud/batchDownload', {idList:ids}, {responseType: 'blob',})
  const url = window.URL.createObjectURL(new Blob([res]));
  // 创建一个临时的 <a> 标签，模拟点击下载
  const link = document.createElement('a');
  link.href = url;
  let file_name = moment(new Date()).format('YYYY-MM-DD HH:mm')
  link.setAttribute('download', `${file_name}.zip`); // 设置下载文件的名称
  document.body.appendChild(link);
  link.click(); // 模拟点击下载链接

  // 清理资源
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url); // 释放 Blob 对象占用的内存

  ElMessage.success('操作成功')
  await getFiles()

}

function rename() {
  if (!selection.value.length) return
  selection.value.forEach(item => {
    item.newName = item.name
    item.is_rename = true
  })
}

function toDelete(v, item) {
  let arr = item ? [item] : getSelection()
  console.log(arr,item,showType.value)
  if (!arr.length) return
  ElMessageBox.confirm(
      `确认${v === 1 ? '删除' : '恢复'}选中的文件或文件夹？`,
      '提醒',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        await local.post('/cloud/delCloudFiles', {del_flag: v, ids: arr.map(el => el.id).join()})
        ElMessage.success(v === 1 ? '删除成功' : '恢复成功')
        await getFiles()
      })
      .catch(() => {

      })
}

function completelyDelete(item) {
  let arr = item ? [item] : getSelection()
  if (!arr.length) return
  ElMessageBox.confirm(
      '确认彻底删除选中的文件或文件夹？',
      '提醒',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        await local.post('/cloud/completelyDelete', {
          fileList: arr.map(el => {
            return {
              path: el.path,
              id: el.id
            }
          })
        })
        ElMessage.success('删除成功')
        await getFiles()
      })
      .catch(() => {

      })
}

async function changePath(id, i) {
  if (parent_id.value === id) return
  file_path.value = id ? file_path.value.slice(0, i + 1) : []
  parent_id.value = id
  await getFiles()
}

async function goFolder(row) {
  if (row.is_folder === 1) {
    file_path.value.push(row)
    parent_id.value = row.id
    await getFiles()
  } else {
    filePreviewRef.value?.show(row)
  }
}

function setType(item) {
  selectType.value = item.type
  getFiles()
}


async function getFiles() {
  let {data} = await local.get('/cloud/getCloudFiles', {
    params: {
      type: selectType.value,
      parent_id: parent_id.value
    }
  })
  data.forEach(el => {
    el.create_time = moment(el.create_time).format('YYYY-MM-DD HH:mm:ss')
    el.update_time = moment(el.update_time).format('YYYY-MM-DD HH:mm:ss')
    el.size = el.is_folder === 1 ? '-' : utils.renderSize(el.size)
  })
  dataList.value = data
}

function onselectionchange(v) {
  selection.value = v
}

async function getDictItems() {
  let {data} = await axios.get({url: 'dictionary/code/file_type'})
  nav.value = [
    {
      name: '全部文件',
      icon: 'iconfont icon-suoyouwenjian',
      type: 'all'
    },
    ...data.file_type.map(el => {
      return {
        name: el.name,
        icon: el.params,
        type: el.value
      }
    }),
    {
      name: '回收站',
      icon: 'iconfont icon-huishouzhan',
      type: 'delete'
    },
  ]
}
function taskAppend(item) {
  taskRef.value.appendTask(item)
}
getDictItems()
getFiles()
</script>

<template>
  <div class="cloud">
    <div class="top-nav">
      <ul>
        <li @click="setType(item)" :class="{'active':item.type===selectType}" v-for="item in nav" :key="item.type">
          <i v-if="selectType===item.type" :class="item.icon"></i>
          <span>{{ item.name }}</span>
        </li>
      </ul>
    </div>
    <div class="btn-group">
      <div class="input">
        <ul v-if="selectType!=='delete'">
          <li @click="changePath(null)">
            根目录 <span style="color: gray"> > </span>
          </li>
          <li @click="changePath(item.id,i)" :class="{'active':i<file_path.length}" v-for="(item,i) in file_path">
            {{ item.name }} <span style="color: gray" v-if="i!==file_path.length"> > </span>
          </li>
        </ul>
      </div>
      <div>
        <el-button-group v-if="selectType!=='delete'" style="margin-right: 10px" size="small" class="ml-4">
          <el-button round @click="createOrUploadRef.show('file',parent_id)" type="success" :icon="Upload">上传
          </el-button>
          <el-button v-if="showType==='grid'" round @click="rename" type="primary" :icon="Edit">重命名</el-button>
          <el-button round @click="move()" type="primary" :icon="Rank">移动</el-button>
          <el-button round @click="toDelete(1)" type="danger" :icon="Delete">删除</el-button>
          <el-button round @click="batchDownload()" type="primary" :icon="Download">下载</el-button>
        </el-button-group>
        <el-button-group v-else style="margin-right: 10px" size="small" class="ml-4">
          <el-button round @click="toDelete(0)" type="warning" :icon="RefreshLeft">恢复</el-button>
          <el-button round @click="completelyDelete()" type="danger" :icon="Delete">彻底删除</el-button>
        </el-button-group>
      </div>
      <el-radio-group style="margin-right: 10px" size="small" v-model="showType">
        <el-radio-button value="grid">
          <el-icon title="列表模式">
            <Grid/>
          </el-icon>
        </el-radio-button>
        <el-radio-button value="folder">
          <el-icon title="文件模式">
            <Folder/>
          </el-icon>
        </el-radio-button>
      </el-radio-group>
    </div>
    <div class="data-div">
      <el-table v-if="showType==='grid'" @selection-change="onselectionchange" height="100%" highlight-current-row
                :data="dataList">
        <el-table-column align="center" width="40px" label="" type="selection"/>
        <el-table-column align="left" label="文件名" prop="name">
          <template #default="{row}">
            <div :title="row.desc" v-if="!row.is_rename" @click="goFolder(row)" class="folder">
              <img :src="utils.imgSrc(row)" alt="">
              <span>{{ row.name }}</span>
            </div>
            <div v-else class="rename">
              <el-input style="width: 60%;" size="default" show-word-limit maxlength="255" v-model="row.newName"
                        clearable></el-input>
              <el-button @click="updateName(row)" size="small" type="success" style="margin-left: 15px" circle
                         :icon="Check"></el-button>
              <el-button @click="row.is_rename=false" size="small" circle :icon="Close"></el-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column align="center" width="120px" label="大小" prop="size"/>
        <el-table-column align="center" width="200px" label="创建时间" prop="create_time"/>
        <el-table-column align="center" width="200px" label="修改时间" prop="update_time"/>
      </el-table>
      <card-warp ref="cardRef" @download="batchDownload" @remove="move"
                 @preview="goFolder" @delete="(item)=>toDelete(1,item)" @restore="(item)=>toDelete(0,item)"
                 @complete-delete="completelyDelete" v-else :data="dataList"/>
    </div>
    <create-or-upload @task_success="taskAppend" :file_path="file_path" @success="getFiles" :file_type="nav" ref="createOrUploadRef"/>
    <move-to-folder :file_path="file_path" @success="resetSearch" ref="moveRef"/>
    <file-preview ref="filePreviewRef"/>
  </div>
</template>

<style scoped lang="scss">
.folder {
  display: flex;
  align-items: center;

  &:hover {
    color: var(--el-color-primary);
  }

  img {
    width: 30px;
    height: auto;
  }

  span {
    margin-left: 15px;
    cursor: pointer;
  }
}

.cloud {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .btn-group {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;

    .input {
      flex: 1;
      flex-shrink: 0;
      overflow: hidden;
      display: flex;
      justify-content: flex-start;

      ul {
        display: flex;
        align-items: center;

        .active {
          color: #409eff;
        }

        li {
          transition: all .2s;
          margin-right: 6px;
          cursor: pointer;
          font-size: 14px;
          color: gray;
        }
      }

    }
  }

  .data-div {
    flex: 1;
    flex-shrink: 0;
    padding: 10px;
    overflow: hidden;
  }

  .top-nav {
    display: flex;
    background-color: #ececec;


    ul {
      display: flex;
      justify-content: center;
      width: 100%;
      padding: 10px 0;

      .active {
        background-color: #409eff;
        color: white;
      }

      li {
        cursor: pointer;
        padding: 10px 20px;
        font-size: 15px;
        display: flex;
        align-items: center;
        transition: all 0.5s;

        i {
          margin-right: 5px;
          font-size: 16px;
        }
      }
    }
  }
}
</style>
